package com.wzq.animal.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.animal.back.pojo.Role;
import com.wzq.animal.back.pojo.RolePermission;
import com.wzq.animal.back.service.RolePermissionService;
import com.wzq.animal.back.service.RoleService;
import com.wzq.animal.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @GetMapping("/getPages/{currentPage}/{pageSize}")
    public Result getPages(@PathVariable("currentPage") int currentPage,
                           @PathVariable("pageSize") int pageSize,
                           @RequestParam("name") String name,
                           @RequestParam("comment") String comment) {
        Page<Role> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Role::getName,name)
                .like(Role::getComment,comment);
        roleService.page(page, queryWrapper);
        return Result.success(page);
    }

    @PostMapping("/saveOrUpdateRole")
    public Result saveOrUpdatePermission(@RequestBody Role role){
        roleService.saveOrUpdate(role);
        Integer id = role.getId();
        if(StringUtils.isNotBlank(id.toString())){
            Role updatedRole = roleService.getById(id);
            return Result.success(updatedRole);
        }
        return Result.success();
    }

    @DeleteMapping("/delRole/{id}")
    public Result delPermission(@PathVariable("id") int id) {
        roleService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delBatchRole")
    public Result delBatch(@RequestBody List<Integer> ids) {
        roleService.removeByIds(ids);
        return Result.success();
    }

    /**
     * 查询角色权限
     * @param id 角色 id
     * @return
     */
    @GetMapping("/selectedPermission/{id}")
    public Result selectedPermission(@PathVariable("id") Integer id){
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId,id);
        List<RolePermission> list = rolePermissionService.list(queryWrapper);
        List<Integer> permissionIds = new ArrayList<>();
        for(RolePermission r : list){
            permissionIds.add(r.getPermissionId());
        }
        return Result.success(permissionIds);
    }
}
